package 极客算法训练营.chapter03;

/**
 *反转一个单链表。
 *
 * 示例:
 *
 * 输入: 1->2->3->4->5->NULL
 * 输出: 5->4->3->2->1->NULL
 */
public class 反转链表 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {

    }
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    private static ListNode pre = null, next = null;
    public static ListNode reverseList2(ListNode head) {
        if (head == null) {
            return pre;
        }

        next = head.next;
        head.next = pre;

        pre = head;
        head = next;
        return reverseList2(head);


    }
}


